package com.atguigu.lease.web.admin.service.impl;

import com.atguigu.lease.common.GlobalExceptionHandler.CustomException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.model.entity.*;
import com.atguigu.lease.model.enums.ItemType;
import com.atguigu.lease.model.enums.ReleaseStatus;
import com.atguigu.lease.web.admin.mapper.*;
import com.atguigu.lease.web.admin.service.ApartmentInfoService;

import com.atguigu.lease.web.admin.vo.apartment.ApartmentDetailVo;
import com.atguigu.lease.web.admin.vo.apartment.ApartmentItemVo;
import com.atguigu.lease.web.admin.vo.apartment.ApartmentQueryVo;
import com.atguigu.lease.web.admin.vo.apartment.ApartmentSubmitVo;

import com.atguigu.lease.web.admin.vo.graph.GraphVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ApartmentInfoServiceImpl extends ServiceImpl<ApartmentInfoMapper, ApartmentInfo> implements ApartmentInfoService {
    @Autowired
    private ApartmentInfoMapper apartmentInfoMapper;

    @Autowired
    private ApartmentFacilityMapper apartmentFacilityMapper;

    @Autowired
    private ApartmentFeeValueMapper apartmentFeeValueMapper;

    @Autowired
    private ApartmentLabelMapper apartmentLabelMapper;

    @Autowired
    private GraphInfoMapper graphInfoMapper;

    @Autowired
    private ProvinceInfoMapper provinceInfoMapper;
    @Autowired
    private CityInfoMapper cityInfoMapper;
    @Autowired
    private DistrictInfoMapper districtInfoMapper;

    @Autowired
    private RoomInfoMapper roomInfoMapper;

    @Override
    public boolean saveOrUpdateApartment(ApartmentSubmitVo apartmentSubmitVo) {
       /* 思路:公寓信息判断有无id, 没id就新增,有id就更新,
        下面的其它字段(配套,费用,标签,图片),无论有没有,一律先删再增.*/

        //设置省name
        apartmentSubmitVo.setProvinceName(provinceInfoMapper.selectById(apartmentSubmitVo.getProvinceId()).getName());
        //设置市name
        apartmentSubmitVo.setCityName(cityInfoMapper.selectById(apartmentSubmitVo.getCityId()).getName());
        //设置市name
        apartmentSubmitVo.setDistrictName(districtInfoMapper.selectById(apartmentSubmitVo.getDistrictId()).getName());

        if (apartmentSubmitVo.getId() == null) {
            //id为null要新增
            apartmentInfoMapper.insert(apartmentSubmitVo);
        } else {
            apartmentInfoMapper.updateById(apartmentSubmitVo);
        }
        //问题:为啥这里调不了saveOrUpdate方法?
        //apartmentInfoMapper.saveOrUpdate(apartmentSubmitVo);



        // 更新关联表数据
        updateFacilities(apartmentSubmitVo.getId(), apartmentSubmitVo.getFacilityInfoIds());
        updateFeeValues(apartmentSubmitVo.getId(), apartmentSubmitVo.getFeeValueIds());
        updateLabels(apartmentSubmitVo.getId(), apartmentSubmitVo.getLabelIds());
        updateGraphInfo(apartmentSubmitVo.getId(), apartmentSubmitVo.getGraphVoList());
        return true;
    }

    /**
     * 更新公寓设施信息
     *
     * @param apartmentId     公寓ID
     * @param facilityInfoIds 设施ID列表
     */
    private void updateFacilities(Long apartmentId, List<Long> facilityInfoIds) {
        if (facilityInfoIds == null) return;
        apartmentFacilityMapper.delete(Wrappers.<ApartmentFacility>lambdaQuery().eq(ApartmentFacility::getApartmentId, apartmentId));
        // 插入新的关联数据
        for (Long facilityId : facilityInfoIds) {
            ApartmentFacility apartmentFacility = ApartmentFacility.builder()
                    .apartmentId(apartmentId)
                    .facilityId(facilityId)
                    .build();
            apartmentFacilityMapper.insert(apartmentFacility);
        }
    }

    /**
     * 更新公寓收费项
     *
     * @param apartmentId 公寓ID
     * @param feeValueIds 收费项ID列表
     */
    private void updateFeeValues(Long apartmentId, List<Long> feeValueIds) {
        if (feeValueIds == null) return;

        // 删除现有的关联数据
        apartmentFeeValueMapper.delete(new QueryWrapper<ApartmentFeeValue>().eq("apartment_id", apartmentId));

        // 插入新的关联数据
        for (Long feeValueId : feeValueIds) {
            ApartmentFeeValue apartmentFeeValue = ApartmentFeeValue.builder()
                    .apartmentId(apartmentId)
                    .feeValueId(feeValueId)
                    .build();
            apartmentFeeValueMapper.insert(apartmentFeeValue);
        }
    }

    /**
     * 更新公寓标签
     *
     * @param apartmentId 公寓ID
     * @param labelIds    标签ID列表
     */
    private void updateLabels(Long apartmentId, List<Long> labelIds) {
        if (labelIds == null) return;

        // 删除现有的关联数据
        apartmentLabelMapper.delete(new QueryWrapper<ApartmentLabel>().eq("apartment_id", apartmentId));

        // 插入新的关联数据
        for (Long labelId : labelIds) {
            ApartmentLabel apartmentLabel = ApartmentLabel.builder()
                    .apartmentId(apartmentId)
                    .labelId(labelId)
                    .build();
            apartmentLabelMapper.insert(apartmentLabel);
        }
    }

    /**
     * 更新公寓图片信息
     *
     * @param apartmentId 公寓ID
     * @param graphVoList 图片信息列表
     */
    private void updateGraphInfo(Long apartmentId, List<GraphVo> graphVoList) {
        if (graphVoList == null) return;

        // 删除现有的图片信息
        graphInfoMapper.delete(new QueryWrapper<GraphInfo>().eq("item_id", apartmentId).eq("item_type", 1));

        // 插入新的图片数据
        for (GraphVo graphVo : graphVoList) {
            GraphInfo graphInfo = new GraphInfo();
            graphInfo.setItemId(apartmentId);
            graphInfo.setItemType(ItemType.APARTMENT);  // 表示公寓
            graphInfo.setName(graphVo.getName());
            graphInfo.setUrl(graphVo.getUrl());
            graphInfoMapper.insert(graphInfo);
        }
    }


    //查询所有分页
    @Override
    public IPage<ApartmentItemVo> selectAllPage(IPage<ApartmentItemVo> page, ApartmentQueryVo apartmentQueryVo) {
        return apartmentInfoMapper.selectAllPage(page,apartmentQueryVo);
    }

    @Override
    public ApartmentDetailVo getDetailById(Long id) {
        return apartmentInfoMapper.getDetailById(id);
    }

    @Override
    public boolean updateReleaseStatusById(Long id, ReleaseStatus status) {
        UpdateWrapper<ApartmentInfo> apartmentInfoUpdateWrapper = new UpdateWrapper<>();
        apartmentInfoUpdateWrapper.eq("id", id);
        apartmentInfoUpdateWrapper.set("is_release", status.getCode());
        return this.update(apartmentInfoUpdateWrapper) ? true : false;
    }

    @Override
    public boolean removeApartmentById(Long id) {
        // 1. 查询公寓信息
        ApartmentInfo apartmentInfo = apartmentInfoMapper.selectById(id);
        // 2. 检查公寓下是否有房间
        LambdaQueryWrapper<RoomInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(RoomInfo::getApartmentId, id);
        queryWrapper.eq(RoomInfo::getIsDeleted, 0); // 未删除的房间
        long roomCount = roomInfoMapper.selectCount(queryWrapper);

        if (roomCount > 0) {
            throw new CustomException(ResultCodeEnum.DELETE_ERROR, "请先删除子集");
        }

        // 3. 执行软删除
        apartmentInfo.setIsDeleted((byte) 1); // 设置为已删除 [[2]](https://poe.com/citation?message_id=368526781619&citation=2)
        int result = apartmentInfoMapper.updateById(apartmentInfo);


        //4.删除公寓相关的数据
        apartmentFacilityMapper.delete(Wrappers.<ApartmentFacility>lambdaQuery().eq(ApartmentFacility::getApartmentId, id));
        apartmentFeeValueMapper.delete(new QueryWrapper<ApartmentFeeValue>().eq("apartment_id", id));
        apartmentLabelMapper.delete(new QueryWrapper<ApartmentLabel>().eq("apartment_id", id));
        graphInfoMapper.delete(new QueryWrapper<GraphInfo>().eq("item_id", id));

        return result > 0;
    }

    @Override
    public List<ApartmentInfo> listInfoByDistrictId(Long id) {
        // 构建查询条件：district_id等于传入的ID且未删除的记录
        LambdaQueryWrapper<ApartmentInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ApartmentInfo::getDistrictId, id)
                .eq(ApartmentInfo::getIsDeleted, 0); // 软删除：只查询未删除的记录
        // 执行查询并返回结果
        return baseMapper.selectList(queryWrapper);
    }
}

